package cn.dankal.flyaudio.store;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.blankj.utilcode.util.StringUtils;
import com.jeremyliao.liveeventbus.LiveEventBus;
import com.jyj.recruitment.wxapi.WxConstants;

import java.text.DecimalFormat;
import java.util.List;

import androidx.annotation.Nullable;
import androidx.lifecycle.Observer;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import api.ShopUserServiceFactory;
import cn.dankal.basiclib.DKUserManager;
import cn.dankal.basiclib.base.activity.BaseActivity;
import cn.dankal.basiclib.common.bus.LiveDataBusConstants;
import cn.dankal.basiclib.domain.HttpStatusCode;
import cn.dankal.basiclib.exception.LocalException;
import cn.dankal.basiclib.pojo.AddressEntity;
import cn.dankal.basiclib.pojo.BaseResponse;
import cn.dankal.basiclib.pojo.CreateOrderPreviewEntity;
import cn.dankal.basiclib.pojo.ProductDetailItemEntity;
import cn.dankal.basiclib.pojo.UserScoresEntity;
import cn.dankal.basiclib.pojo.req.CreateOrderReq;
import cn.dankal.basiclib.util.ActivityUtils;
import cn.dankal.basiclib.util.SimpleTextChange;
import cn.dankal.basiclib.util.ToastUtils;
import cn.dankal.flyaudio.R;
import cn.dankal.flyaudio.adapter.ConfirmOrderProductAdapter;
import cn.dankal.flyaudio.configs.LiveDataBusConstant;
import cn.dankal.flyaudio.configs.PayConfigs;
import cn.dankal.flyaudio.contract.ConfirmOrderContract;
import cn.dankal.flyaudio.entity.ShoppingOrderEntity;
import cn.dankal.flyaudio.friend.pickimage.StringUtil;
import cn.dankal.flyaudio.personal.AddressManagerActivity;
import cn.dankal.flyaudio.pop.PayMethodPop;
import cn.dankal.flyaudio.presenter.ConfirmOrderPresenter;
import io.reactivex.disposables.Disposable;
import razerdp.basepopup.BasePopupWindow;

import static com.jyj.recruitment.wxapi.WxConstants.PAY_FAILED;
import static com.jyj.recruitment.wxapi.WxConstants.PAY_SUCCESS;

public class ConfirmOrderActivity extends BaseActivity implements ConfirmOrderContract.View, View.OnClickListener {

    public static final int REQUEST_PICK_ADDRESS = 18;

    private ConfirmOrderPresenter mPresenter;

    private TextView emptyAddressView;

    private TextView addressNamePhoneView;

    private RecyclerView productList;

    private TextView addressView;

    private TextView amountPayView;
    private TextView scorePricePayView;

    private TextView productAmountView;
    private TextView productFaretView;
    private TextView amountBottomView;
    private EditText customScoreView;
    private TextView productDiscounttView;

    private PayReceive receive = new PayReceive();

    private TextView payMethodView;
    DecimalFormat df = new DecimalFormat("######0.00");

    private int payMethod = 0;

    private String uuid = "";

    private TextView scoreView;

    private CreateOrderReq req = new CreateOrderReq();

    private ShoppingOrderEntity shoppingOrderEntity;

    private EditText remarkView;

    private ConfirmOrderProductAdapter adapter;

    private int useScore = 0;

    private double usePrice = 0.00;

    private int userHasScores = 0;

    private double productAmount = 0.00;

    private Handler handler = new Handler();
    private Runnable delayRunnable = new Runnable() {
        @Override
        public void run() {
            if (StringUtils.isEmpty(customScoreView.getText().toString().trim())) {
                return;
            }
            int use = Integer.parseInt(customScoreView.getText().toString().trim());
            if (use > canUsedScores) {
                ToastUtils.showShort("超过商品可以使用的积分");
//                customScoreView.setText("0");
                return;
            }
            if (use > userHasScores) {
                ToastUtils.showShort("超过您当前拥有的积分");
//                customScoreView.setText(userHasScores);
                return;
            }

            req.setUseScore(customScoreView.getText().toString());
            mPresenter.createOrderPreview(req);
        }
    };

    @Override
    protected int getLayoutId() {
        return R.layout.activity_confirm_order;
    }

    @Override
    protected void initComponents() {
        addSingleTitleBar("确认订单");
        shoppingOrderEntity = (ShoppingOrderEntity) getIntent().getSerializableExtra("products");
        mPresenter = new ConfirmOrderPresenter();
        mPresenter.attachView(this);
        emptyAddressView = findViewById(R.id.tv_no_address_hint);
        scorePricePayView = findViewById(R.id.tv_score_price_pay);
        productFaretView = findViewById(R.id.tv_product_fare);
        scoreView = findViewById(R.id.tv_user_score);
        amountBottomView = findViewById(R.id.tv_amount_bottom);
        customScoreView = findViewById(R.id.et_custom_score);
        userHasScores = Integer.parseInt(DKUserManager.getUserScores().getUsable());
        scoreView.setText(userHasScores + "");
        productDiscounttView = findViewById(R.id.tv_product_coupon);
        addressNamePhoneView = findViewById(R.id.tv_address_name_phone);
        productList = findViewById(R.id.product_list);
        productList.setLayoutManager(new LinearLayoutManager(this));
        adapter = new ConfirmOrderProductAdapter();
        productList.setAdapter(adapter);
//        adapter.addDatas(shoppingOrderEntity.getProducts(), true);
        addressView = findViewById(R.id.tv_address);
        amountPayView = findViewById(R.id.tv_amount_pay);
        remarkView = findViewById(R.id.et_remark);
        productAmountView = findViewById(R.id.tv_product_amount);
        payMethodView = findViewById(R.id.tv_pay_method);
        findViewById(R.id.tv_confirm).setOnClickListener(this);
        findViewById(R.id.rl_pay_method).setOnClickListener(this);
        findViewById(R.id.ll_select_address).setOnClickListener(this);
        scorePricePayView.setOnClickListener(this);
        amountPayView.setOnClickListener(this);
        mPresenter.getMyAddress();
        init();
        amountPayView.setSelected(true);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(PAY_FAILED);
        intentFilter.addAction(PAY_SUCCESS);
        fetchUserScores();
        LiveEventBus.get(LiveDataBusConstant.DELETE_SHOPPING_CART_ADDRESS, String.class).observe(this, new Observer<String>() {
            @Override
            public void onChanged(String s) {
                if (!StringUtils.isEmpty(req.getAddressUuid())) {
                    if (StringUtils.equals(req.getAddressUuid(), s)) {
                        //删除地址是当前已经选中的地址
                        req.setAddressUuid("");
                        emptyAddressView.setVisibility(View.VISIBLE);
                        addressNamePhoneView.setVisibility(View.GONE);
                        addressView.setVisibility(View.GONE);
//                        mPresenter.createOrderPreview(req);
                    }
                }
            }
        });
        customScoreView.addTextChangedListener(new SimpleTextChange() {
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                if (delayRunnable != null) {
                    handler.removeCallbacks(delayRunnable);
                }
                if (!StringUtil.isEmpty(s.toString())) {
                    customScoreView.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_coin01,
                            0, 0, 0);
                } else {
                    customScoreView.setCompoundDrawablesWithIntrinsicBounds(R.mipmap.ic_coin02,
                            0, 0, 0);
                }
            }

            @Override
            public void afterTextChanged(Editable s) {
                handler.postDelayed(delayRunnable, 500);
            }
        });
        LocalBroadcastManager.getInstance(this).registerReceiver(receive, intentFilter);
    }

    private double amount = 0;
    private int count = 0;

    private void init() {
        req.setItems(shoppingOrderEntity.getItemReq());
        req.setAddressUuid("");
    }

    public void fetchUserScores() {
        ShopUserServiceFactory.userScores().subscribe(new io.reactivex.Observer<BaseResponse<UserScoresEntity>>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse<UserScoresEntity> userScoresEntityBaseResponse) {
                DKUserManager.updateUserInfoScores(userScoresEntityBaseResponse.getData());
                LiveEventBus.get(LiveDataBusConstants.REFRESH_USER_SCORES, String.class).post("");
                userHasScores = Integer.parseInt(DKUserManager.getUserScores().getUsable());
                scoreView.setText(userHasScores + "");
            }

            @Override
            public void onError(Throwable e) {
                if (e instanceof LocalException) {
                    LocalException exception = (LocalException) e;
                    //401 重新获取access token , 如果还返回412 就是refresh token 也失效了。需要重新登录
                    if (exception.getErrorCode() == HttpStatusCode.TOKEN_INVAILD ||
                            exception.getErrorCode() == HttpStatusCode.UNAUTHORIZED) {
                        //view.showToast("登录信息失效");
                    } else {
                    }
                } else {
                    Log.e("SubscriberThrowable", e.getMessage());
                }
            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        LocalBroadcastManager.getInstance(this).unregisterReceiver(receive);
        mPresenter.detachView();
    }

    @Override
    public void handleAddressList(List<AddressEntity> addressEntities) {
        if (addressEntities.isEmpty()) {
            //请选择收货地址
            emptyAddressView.setVisibility(View.VISIBLE);
            addressNamePhoneView.setVisibility(View.GONE);
            addressView.setVisibility(View.GONE);
            mPresenter.createOrderPreview(req);
            return;
        }
        AddressEntity addressEntity = null;
        for (AddressEntity entity : addressEntities) {
            if (entity.getDefaultAddress()) {
                addressEntity = entity;
            }
        }
        //如果有地址列表，没有默认地址选项，取第一个
        if (addressEntity == null) {
            addressEntity = addressEntities.get(0);
        }
        req.setAddressUuid(addressEntity.getUuid());
        mPresenter.createOrderPreview(req);
        emptyAddressView.setVisibility(View.GONE);
        addressNamePhoneView.setVisibility(View.VISIBLE);
        addressView.setVisibility(View.VISIBLE);
        addressNamePhoneView.setText(addressEntity.getContacter() + "  " + addressEntity.getPhone());
        addressView.setText(addressEntity.getProvince() + addressEntity.getCity() + addressEntity.getRegion() + addressEntity.getAddressDetail());
    }

    private int canUsedScores = 0;

    @Override
    public void handlePreview(CreateOrderPreviewEntity entity) {
        adapter.addDatas(entity.getOrderItemList(), true);
        amount = entity.getDiscountAmount();
        usePrice = entity.getNeedPay();
        productAmountView.setText("¥" + df.format(Double.valueOf(entity.getDiscountedPrice())));
        productFaretView.setText("¥" + entity.getDiscountAmount());
        productDiscounttView.setText("¥" + entity.getShippingPrice());
        scorePricePayView.setText(entity.getUsedScore() + " +¥ " + df.format(usePrice));
        useScore = entity.getUsedScore();
        canUsedScores = 0;
        for (ProductDetailItemEntity itemEntity : entity.getOrderItemList()) {
            canUsedScores += Integer.parseInt(itemEntity.getCanUseScore());
        }
        DecimalFormat decimalFormat = new DecimalFormat("#.##");
        productAmount = Double.parseDouble(entity.getDiscountedPrice()) + Double.parseDouble(entity.getShippingPrice());
        amountPayView.setText("¥" + decimalFormat.format(productAmount));
        amountBottomView.setText(amountPayView.getText().toString());
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch (id) {
            case R.id.tv_score_price_pay:
                scorePricePayView.setSelected(true);
                amountPayView.setSelected(false);
                amountBottomView.setText(useScore + "+¥" + df.format(usePrice));
                break;
            case R.id.tv_amount_pay:
                scorePricePayView.setSelected(false);
                amountPayView.setSelected(true);
                amountBottomView.setText(amountPayView.getText().toString());
                break;
            case R.id.ll_select_address:
                Intent intent = new Intent(this, AddressManagerActivity.class);
                intent.putExtra("is_pick", true);
                startActivityForResult(intent, REQUEST_PICK_ADDRESS);
                break;
            case R.id.rl_pay_method:
                break;
            case R.id.tv_confirm:
                if (TextUtils.isEmpty(req.getAddressUuid())) {
                    ToastUtils.showShort("请选择收货地址");
                    return;
                }
                if (scorePricePayView.isSelected()) {
                    req.setUseScore(useScore + "");
                } else {
                    req.setUseScore("0");
                }
                req.setUserMessage(remarkView.getText().toString());
                if (usePrice == 0 && !amountPayView.isSelected()) {
                    mPresenter.createOrder(req, ConfirmOrderPresenter.PAY_TYPE_NO_PAY);
                } else {
                    PayMethodPop payMethodPop = new PayMethodPop(this);
                    payMethodPop.setOnDismissListener(new BasePopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            payMethod = payMethodPop.getPayMethod();

                            if (payMethod == PayConfigs.PAY_METHOD_ALIPAY) {
                                mPresenter.createOrder(req, ConfirmOrderPresenter.PAY_TYPE_ALIPAY);
                                return;
                            }
                            if (payMethod == PayConfigs.PAY_METHOD_WECHAT) {
                                mPresenter.createOrder(req, ConfirmOrderPresenter.PAY_TYPE_WECHAT);
                                return;
                            }
//                        mPresenter.createOrder(req, ConfirmOrderPresenter.PAY_TYPE_NO_PAY);
                        }
                    });
                    payMethodPop.showPopupWindow(findViewById(android.R.id.content));
                }
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_PICK_ADDRESS) {
            if (resultCode == RESULT_OK) {
                AddressEntity addressEntity = (AddressEntity) data.getSerializableExtra("address");
                req.setAddressUuid(addressEntity.getUuid());
                mPresenter.createOrderPreview(req);
                emptyAddressView.setVisibility(View.GONE);
                addressNamePhoneView.setVisibility(View.VISIBLE);
                addressView.setVisibility(View.VISIBLE);
                addressNamePhoneView.setText(addressEntity.getContacter() + "  " + addressEntity.getPhone());
                addressView.setText(addressEntity.getProvince() + addressEntity.getCity() + addressEntity.getRegion() + addressEntity.getAddressDetail());
            }
        }
    }

    class PayReceive extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            LiveEventBus.get("create_order_success", String.class).post("");
            LiveEventBus.get("ShopCarNum", String.class).post("");
            if (TextUtils.equals(intent.getAction(), WxConstants.PAY_SUCCESS)) {
                Intent jump = new Intent(ActivityUtils.getTopActivity(), PayResultActivity.class);
                jump.putExtra("isPaySuccess", true);
                jump.putExtra("orderUuid", mPresenter.getUuid());
                ActivityUtils.startActivity(jump);
                finish();
            } else if (TextUtils.equals(intent.getAction(), PAY_FAILED)) {
                Intent jump = new Intent(ActivityUtils.getTopActivity(), PayResultActivity.class);
                jump.putExtra("isPaySuccess", false);
                jump.putExtra("orderUuid", mPresenter.getUuid());
                ActivityUtils.startActivity(jump);
                finish();
            }
        }
    }
}
